// app.js
App({
  globalData: {
    userInfo: null,
    token: null,
    baseUrl: 'https://api.sys-architect.com/v1'
  },

  onLaunch() {
    // 获取本地存储的token
    const token = wx.getStorageSync('token');
    if (token) {
      this.globalData.token = token;
      // 验证token有效性
      this.checkToken();
    }
  },

  // 检查token是否有效
  checkToken() {
    const token = this.globalData.token;
    if (!token) return;

    wx.request({
      url: `${this.globalData.baseUrl}/users/profile`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.statusCode === 200) {
          this.globalData.userInfo = res.data.data;
        } else {
          // token无效，清除存储
          this.clearToken();
        }
      },
      fail: () => {
        this.clearToken();
      }
    });
  },

  // 清除token
  clearToken() {
    this.globalData.token = null;
    this.globalData.userInfo = null;
    wx.removeStorageSync('token');
  },

  // 统一请求方法
  request(options) {
    const token = this.globalData.token;
    const header = {
      'Content-Type': 'application/json',
      ...options.header
    };
    
    if (token) {
      header['Authorization'] = `Bearer ${token}`;
    }

    return new Promise((resolve, reject) => {
      wx.request({
        url: `${this.globalData.baseUrl}${options.url}`,
        method: options.method || 'GET',
        data: options.data,
        header: header,
        success: (res) => {
          if (res.statusCode === 401) {
            // token过期或无效
            this.clearToken();
            // 跳转到登录页
            wx.navigateTo({
              url: '/pages/login/login'
            });
            reject(new Error('未授权'));
          } else if (res.statusCode >= 200 && res.statusCode < 300) {
            resolve(res.data);
          } else {
            reject(res);
          }
        },
        fail: reject
      });
    });
  },

  // 显示加载提示
  showLoading(title = '加载中') {
    wx.showLoading({
      title: title,
      mask: true
    });
  },

  // 隐藏加载提示
  hideLoading() {
    wx.hideLoading();
  },

  // 显示成功提示
  showSuccess(title = '操作成功') {
    wx.showToast({
      title: title,
      icon: 'success',
      duration: 2000
    });
  },

  // 显示错误提示
  showError(title = '操作失败') {
    wx.showToast({
      title: title,
      icon: 'error',
      duration: 2000
    });
  }
})
